<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Screenshot</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>

<body>
  <!-- 待截屏的区域 -->
  <div id="capture" style="border: 1px solid black; padding: 20px;">
    <h1>这是待截屏的内容</h1>
    <p>这里可以是任意文本或其他 HTML 元素。</p>
  </div>
  <button id="screenshotButton">截屏</button>
  <canvas id="canvas" style="display: none;"></canvas>
  <script>
    const capture = document.getElementById('capture');
    const canvas = document.getElementById('canvas');
    const screenshotButton = document.getElementById('screenshotButton');

    screenshotButton.addEventListener('click', async () => {
      try {
        const capturedCanvas = await html2canvas(capture);
        canvas.width = capturedCanvas.width;
        canvas.height = capturedCanvas.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(capturedCanvas, 0, 0);

        const link = document.createElement('a');
        link.href = canvas.toDataURL('image/png');
        link.download = 'screenshot.png';
        link.click();
      } catch (error) {
        console.error('截屏失败:', error);
      }
    });
  </script>
</body>

</html>